package com.carltechnology.mahjonggamecaculation.utils.views;

import android.content.Context;
import android.support.v4.widget.NestedScrollView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by WZTCM on 2016/7/6.
 */
public class TitleBarDecor extends NestedScrollView{

    /**
     *内容本身,即她的儿子Son
     */
    private ViewGroup mContentView;
    private ViewGroup mRecycleViewGroup;
    private View mStickHeader;
    private int mTopViewTop = 0;
    public TitleBarDecor(Context context) {
        super(context,null);
        init();
    }

    public TitleBarDecor(Context context, AttributeSet attrs) {
        super(context, attrs,0);
    }

    public TitleBarDecor(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        final int y = t;
        post(new Runnable() {
            @Override
            public void run() {

                if (mRecycleViewGroup == null) return;
                if (y>=mTopViewTop&& mStickHeader.getParent()==mRecycleViewGroup){
                    mRecycleViewGroup.removeView(mStickHeader);
                    addView(mStickHeader);
                    System.out.println("change");
                }else if (y<mTopViewTop
                        && mStickHeader.getParent()==TitleBarDecor.this){
                    removeView(mStickHeader);
                    mRecycleViewGroup.addView(mStickHeader);
                    System.out.println("change2");
                }
            }
        });

    }
    private void init(){
        mContentView = null;
        mRecycleViewGroup = null;
        mStickHeader = null;
        post(new Runnable() {
            @Override
            public void run() {
                if (mContentView == null){
                    mContentView = (ViewGroup) getChildAt(0);
                }
                if (mRecycleViewGroup == null){
                    mRecycleViewGroup = (ViewGroup) mContentView.getChildAt(0);
                }
                if (mStickHeader==null){
                    mTopViewTop = mRecycleViewGroup.getTop();
                    mStickHeader = mRecycleViewGroup.getChildAt(0);
                }
            }
        });
    }
}
